package com.janal.util;

import java.sql.*;

public class utils {
        private static String url;
        private static String user;
        private static String password;
//    private static String driver;

        //    使用静态代码块读取文件，获取值
        static {
            url="jdbc:mysql:///mvc-login";
            user="root";
            password="root";
//    try {
//        创建Properties对象
//        Properties pro = new Properties();

//        获取src路径下的配置文件  (不知为何无法成功)
//        ClassLoader classLoader = JDBCUtils.class.getClassLoader();
//        URL res = classLoader.getResource("jdbc.properties");
//        String path = res.getPath();
//        System.out.println(path);

//        加载文件
//        pro.load(new FileReader("jdbc.properties"));

//        获取数据，赋值
//        url = pro.getProperty("url");
//        user = pro.getProperty("user");
//        password = pro.getProperty("password");
//        driver = pro.getProperty("driver");

//    } catch (IOException /*| ClassNotFoundException*/ e) {
//        e.printStackTrace();
//    }
        }

        //    获取连接
        public static Connection getConnection() throws SQLException, ClassNotFoundException {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(url,user,password);
        }


        //    释放资源
        public static void close(PreparedStatement pstm, Connection conn){
            if(pstm != null){
                try {
                    pstm.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

        public static void close(ResultSet rs,PreparedStatement pstm, Connection conn) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (pstm != null) {
                try {
                    pstm.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
}
